﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SportsStore.Data;
using SportsStore.Models;
using SportsStore.Infrastructure;
using SportsStore.Models.ViewModels;

namespace SportsStore.Controllers
{
    public class CartController : Controller
    {
        private IProductRepository repository;
        private Cart cart;

        public CartController(IProductRepository repo,Cart cartService)
        {
            repository = repo;
            cart = cartService;
        }
        public ViewResult Index(string returnUrl)
        {
            return View(new CartIndexViewModel
            {
                Cart=cart,
                ReturnUrl=returnUrl
            });
        }
        public RedirectToActionResult AddToCart(int id,string returnUrl)
        {
            Product product = repository.Products.FirstOrDefault(p => p.Id == id);

            if (product != null)
            {
                cart.AddItem(product, 1);
            }

            return RedirectToAction("Index", new { returnUrl });
        }
        public RedirectToActionResult RemoveFromCart(int id,string returnUrl)
        {
            cart.RemoveLine(new Product() { Id = id });
            return RedirectToAction("Index", new { returnUrl });
        }
    }
}